package com.sinochem.yunlian.ship.common.filter;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.google.common.base.Charsets;
import com.sinochem.yunlian.ship.common.annotation.LimitNumber;
import com.sinochem.yunlian.ship.common.constant.CommonConstants;
import com.sinochem.yunlian.ship.common.constant.RedisKey;
import com.sinochem.yunlian.ship.common.exception.BaseException;
import com.sinochem.yunlian.ship.common.util.CookieHelper;

@Component
public class LimitInterfaceNumber extends HandlerInterceptorAdapter{
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	private Logger LOG = LoggerFactory.getLogger(getClass());
	
	 /**
     * 限制接口访问数字
     * @param request
     * @param handler
     * @return
     */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		 HandlerMethod handlerMethod = (HandlerMethod) handler;
		
		// 配置该注解，说明不进行用户拦截
    	LimitNumber limitNumber  = handlerMethod.getMethodAnnotation(LimitNumber.class);
    	
        if (limitNumber == null) {        	
        	return super.preHandle(request, response, handler); // 不限制次数
        }
    	// 修改成用户id
        String userId = request.getHeader(CommonConstants.CUR_USER_ID);
        
        LOG.info("打印用户id:{}", userId);
        
		if (StringUtils.isBlank(userId)) {
			LOG.error("用户id为空!; id:{}", userId);
			throw new Exception("不存在您的身份信息!");
		}
		// 获取该用户已经访问的次数
		String cachedStr =  (String) redisTemplate.opsForValue().get(RedisKey.LIMIT_INTERFACE_NUMBER + userId);	
		
		int visitTimes = 0;
		
		String requestDateStr = null;
	
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		
		String nowDateStr = simpleDateFormat.format(new Date());
		
		if (StringUtils.isNoneEmpty(cachedStr)) {			
			String[] strs = cachedStr.split(":");			
			if (strs.length == 2) {				
				visitTimes = Integer.parseInt(strs[0]);
				requestDateStr = strs[1]; // 获取第一次请求接口时间				
			} else {				
				return super.preHandle(request, response, handler); 
			}
			
		}

		LOG.info("用户的userId:{} 已经访问的次数及时间: {}",userId, cachedStr);
		
		int limits = limitNumber.limitNumber();
		
		if (requestDateStr == null) {
			requestDateStr = nowDateStr;
		}
		if (visitTimes >= limits && simpleDateFormat.parse(nowDateStr).compareTo(simpleDateFormat.parse(requestDateStr)) == 0) {
			
			throw BaseException.message("今日已达查询上限"); // 当天访问超过限次次数
		} 
		
		if (simpleDateFormat.parse(nowDateStr).compareTo(simpleDateFormat.parse(requestDateStr)) != 0) {
			
			visitTimes = 0;
			requestDateStr = nowDateStr;
		}
		redisTemplate.opsForValue().set(RedisKey.LIMIT_INTERFACE_NUMBER + userId, ++visitTimes + ":" + requestDateStr); // 更新访问次数
		
		// 还可以访问的剩余次数
		request.setAttribute(CommonConstants.RESIDUE_COUNT, limits - visitTimes);
		
		return super.preHandle(request, response, handler); 
	}


}
